<template>
  <el-card class="report-container">
    <div class="report-header">
      <div class="header-date-comp">
        <el-radio-group style="margin-right: 30px" v-model="dateType" @change="time=today">
          <el-radio label="day">按日</el-radio>
          <el-radio label="month">按月</el-radio>
          <el-radio label="year">按年</el-radio>
        </el-radio-group>
        <el-date-picker
          v-if="dateType==='day'"
          v-model="time"
          type="date"
          :clearable="false"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"></el-date-picker>
        <el-date-picker
          v-if="dateType==='month'"
          v-model="time"
          type="month"
          :clearable="false"
          placeholder="选择月份"
          value-format="yyyy-MM"></el-date-picker>
        <el-date-picker
          v-if="dateType==='year'"
          v-model="time"
          type="year"
          :clearable="false"
          placeholder="选择年"
          value-format="yyyy"></el-date-picker>
        <el-button style="margin-left: 10px" type="primary"  @click.native="timeSearch(false)">筛选</el-button>
      </div>
      <div>
        <el-tooltip content="添加到快捷搜索栏">
          <el-button size="mini"  circle @click.native="timeSearch(true)">
            <i class="el-icon-plus" />
          </el-button>
        </el-tooltip>
        <el-tooltip content="导出excel">
          <el-button size="mini"  circle @click.native="remoteExport">
            <svg-icon icon-class="f-export" class-name="im-ex-icon" />
          </el-button>
        </el-tooltip>
      </div>
    </div>
    <div style="width: 100%;margin-top: 30px;margin-bottom: 30px;text-align: center">
      <h3>{{title}}</h3>
    </div>
    <el-tabs v-model="searchTabsValue" type="card" closable @tab-remove="removeTab" @tab-click="clickTimeTab">
      <el-tab-pane
        v-for="(item, index) in searchTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"></el-tab-pane>
    </el-tabs>
    <el-tag type="info">{{subTitle1}}</el-tag>
    <el-row style="width: 100%" :gutter="10">
      <el-col :span="device=='mobile'?24:8">
        <el-table :data="reportData1"
              border
              v-loading="tableLoading"
              element-loading-text="报表生成中..."
              element-loading-spinner="el-icon-loading">
        <el-table-column v-for="(col,idx) in reportCols1" :key="idx" :prop="col.prop" :label="col.label" :type="col.type" :width="col.width" :fixed="col.fixed">
          <el-table-column v-for="(child, index) in col.children" :key="index" :prop="child.prop" :label="child.label" ></el-table-column>
        </el-table-column>
      </el-table>
      </el-col>
      <el-col :span="device=='mobile'?24:16">
        <el-table :data="reportData2"
                border
                v-loading="tableLoading"
                element-loading-text="报表生成中..."
                element-loading-spinner="el-icon-loading">
        <el-table-column v-for="(col,idx) in reportCols2" :key="idx" :prop="col.prop" :label="col.label" :type="col.type" :width="col.width" :fixed="col.fixed">
          <el-table-column v-for="(child, index) in col.children" :key="index" :prop="child.prop" :label="child.label" ></el-table-column>
        </el-table-column>
      </el-table>
      </el-col>
    </el-row>
  </el-card>

</template>

<script>
  import analysisApi from "@/api/analysis"
  import {formMonths} from "@/utils/constants"
  import {parseTime} from "@/utils"
  import {mapGetters} from 'vuex'
  const today = parseTime(new Date(),'{y}-{m}-{d}')
  export default {
    name: "formPanel",
    props:{
      query:{
        type:Object,
        required:true
      }
    },
    data(){
      return {
        title:'**电厂入库量指标统计表',
        subTitle1:'八、化污水指标',
        dateType:'day',
        today,
        formMonths,
        tableLoading:false,
        downloadLoading: false,
        content:'暂无报表数据!',
        reportCols1:[],
        reportData1: [],
        reportCols2:[],
        reportData2: [],
        time:today,
        searchTabsValue:'',
        searchTabsLabel:'',
        searchTabs:[],
        tabIndex:0
      }
    },
    computed:{
      ...mapGetters([
        'device'
      ]),
      excelFileName(){
        return this.title+this.time
      }
    },
    methods:{
      fetchData(save=false){
        if (!this.query.orgnization_id){
          this.$message.warning("请选择组织!")
          this.reportCols1=null
          this.reportData1=null
          this.reportCols2=null
          this.reportData2=null
          return
        }
        let rqParams = Object.assign({},this.query)
        rqParams.time=this.time
        const dateComps = this.time.split('-')
        if (this.dateType==='month'){
          if (dateComps.length>2)
            rqParams.time=`${dateComps[0]}-${dateComps[1]}`
        }else if (this.dateType==='year'){
          if (dateComps.length>2)
            rqParams.time=dateComps[0]
        }

        this.tableLoading=true
        analysisApi.singleReport(rqParams).then(res=>{
          const tableData = this.convertData(res.data)
          this.reportCols1 = tableData[0][0]
          this.reportCols2 = tableData[1][0]
          setTimeout(()=>{
            this.reportData1 = tableData[0][1]
            this.reportData2 = tableData[1][1]
            if (save)
              this.addTab(rqParams.time)
            this.tableLoading=false
          },200)
        })
      },
      timeSearch(withQuick=false){
        if (!withQuick){
          this.searchTabsValue=''
          this.searchTabsLabel=''
          this.fetchData()
          return
        }
        this.$confirm('需要保存到快捷搜索栏吗?', '提示', confirm).then(() => {
          this.fetchData(true)
        }).catch(() => {
          this.searchTabsValue=''
          this.searchTabsLabel=''
          this.fetchData()
        })
      },
      convertData(dataList){
        const table1 = dataList['table1']
        const table2 = dataList['table2']
        let tb1Cols = []
        table1['header'].forEach(col=>{
          tb1Cols.push({
            prop:col.en_name,
            label:col.cn_name,
            children:[],
            fixed:false
          })
        })
        tb1Cols[0].fixed=true
        let tb2Cols = []
        table2['header'].forEach(col=>{
          tb2Cols.push({
            prop:col.en_name,
            label:col.cn_name,
            children:[],
            fixed:false
          })
        })
        tb2Cols[0].fixed=true
        return [[tb1Cols,table1.data],[tb2Cols,table2.data]]
      },
      localExport(){
        import('@/vendor/Export2Excel').then(excel => {
          let multiHeader = []
          let header = []
          for (let col of this.reportCols1){
            if (col.type=='index')
              continue
            header.push(col.label)
          }
          const list = this.reportData1
          const data = list.map(v => Object.values(v))
          const merges = []
          const exportJson={
            filename:this.excelFileName,
            multiHeader,
            header,
            merges,
            data
          }
          excel.export_json_to_excel(exportJson)
          this.$message.success("导出excel成功")
        })
      },
      async remoteExport(){
        const downLoading = this.$loading({
          lock: true,
          text: '导出中...',
          spinner: 'el-icon-loading',
        });
        const token = await this.$store.dispatch('user/refreshToken')
        const baseHost = 'http://analysisapi.wm-mis.com/api'
        let dtm=this.time
        const dateComps = this.time.split('-')
        if (this.dateType==='month'){
          if (dateComps.length>2)
            dtm=`${dateComps[0]}-${dateComps[1]}`
        }else if (this.dateType==='year'){
          if (dateComps.length>2)
            dtm=dateComps[0]
        }
        const durl = `${baseHost}/data-analysis/single-download?token=${token}&orgnization_id=${this.query.orgnization_id}&module_name=${this.query.module_name}&time=${dtm}`
        window.open((durl),"_self")
        setTimeout(()=>{
          downLoading.close()
        },1500)
      },
      clickTimeTab(tab){
        const tab_time = tab.$options.propsData.label
        const dateCompsLen = tab_time.split('-').length
        this.dateType = dateCompsLen>2?'day':dateCompsLen<2?'year':'month'
        this.time = tab_time
        this.fetchData()
      },
      addTab(title) {
        let newTabName = ++this.tabIndex + '';
        this.searchTabs.push({
          title: title,
          name: newTabName
        });
        this.searchTabsValue = newTabName
        this.searchTabsLabel = title
      },
      removeTab(targetName) {
        let tabs = this.searchTabs;
        let activeName = this.searchTabsValue
        let activeLabel = this.searchTabsLabel
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name
                activeLabel = nextTab.title
              }
            }
          });
        }
        this.searchTabsValue = activeName
        this.searchTabsLabel = activeLabel
        this.searchTabs = tabs.filter(tab => tab.name !== targetName);
        this.clickTimeTab({$options:{propsData:{label:activeLabel}}})
      }

    }

  }
</script>

<style scoped lang="scss">
  .report-container{
    padding: 5px;
    .report-header{
      width: 100%;
      height: 60px;
      display: flex;
      flex-direction: row;
      justify-content:space-between;
      align-items: center;
      margin-bottom: 20px;
    }
    .dbl-tables{
      width: 100%;
      display: flex;
      flex-direction: row;
    }

  }
</style>
